package com.qzsoft.zhjd.asphalt.modules.asphaltmatch.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.dto.AsphaltMatchDetsilsDto;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.dto.AsphaltMatchListDto;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.dto.AsphaltMatchSelectDto;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.entity.AsphaltMatchEntity;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.entity.AsphaltMatchNameEntity;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.mapper.AsphaltMatchMapper;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.service.AsphaltMatchColdService;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.service.AsphaltMatchHotService;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.service.AsphaltMatchNameService;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.service.AsphaltMatchService;
import com.qzsoft.zhjd.common.annotation.ZhjdDataFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.common.enums.BizCode;
import com.qzsoft.zhjd.common.utils.RenExceptionUtils;
import com.qzsoft.jeemis.common.utils.ConvertDictUtils;
import com.qzsoft.system.modules.sysstation.entity.SysStationEntity;
import com.qzsoft.system.modules.sysstation.service.SysStationService;
import com.qzsoft.zhjd.asphalt.modules.asphaltdata.entity.AsphaltDataEntity;
import com.qzsoft.zhjd.asphalt.modules.asphaltdata.service.AsphaltDataService;
import org.springframework.util.Assert;

/**
 * @ClassName AsphaltMatchServiceImpl
 * @Description 沥青混合料级配业务接口实现
 * @author linhuawei
 * @since 2021-09-03
 */
@Service
public class AsphaltMatchServiceImpl extends ServiceImpl<AsphaltMatchMapper, AsphaltMatchEntity>
        implements AsphaltMatchService {

    @Autowired
    private BaseServiceComponent baseServiceComponent;

    @Autowired
    private SysStationService sysStationService;

    @Autowired
    private AsphaltMatchNameService asphaltMatchNameService;

    @Autowired
    private AsphaltMatchHotService asphaltMatchHotService;

    @Autowired
    private AsphaltMatchColdService asphaltMatchColdService;

    @Autowired
    private AsphaltDataService asphaltDataService;

    @ZhjdDataFilter(tableAlias = "t1")
    @Override
    public IPage<AsphaltMatchListDto> pageDto(Map<String, Object> params) {
        IPage<AsphaltMatchListDto> page = baseServiceComponent.getPage(params, AsphaltMatchListDto.class);
        page = baseMapper.queryDto(page, params);
        return ConvertDictUtils.formatDicDataPage(page);
    }

    @ZhjdDataFilter
    @Override
    public List<AsphaltMatchEntity> list(Map<String, Object> params) {
        QueryWrapper<AsphaltMatchEntity> queryWrapper = new QueryWrapper<AsphaltMatchEntity>();
        if (ObjectUtils.isNotEmpty(params.get("baseCode"))) {
            queryWrapper.eq("base_code", params.get("baseCode").toString());
        }
        if (ObjectUtils.isNotEmpty(params.get("stationCode"))) {
            queryWrapper.eq("station_code", params.get("stationCode").toString());
        }
        if (ObjectUtils.isNotEmpty(params.get("projectId"))) {
            queryWrapper.eq("project_id", params.get("projectId").toString());
        }
        if (ObjectUtils.isNotEmpty(params.get("matchType"))) {
            queryWrapper.eq("match_type", params.get("matchType").toString());
        }
        if (ObjectUtils.isNotEmpty(params.get("matchName"))) {
            queryWrapper.eq("match_name", params.get("matchName").toString());
        }
        if (ObjectUtils.isNotEmpty(params.get(ZhjdDataFilter.DATA_FILTER_SQL))) {
            queryWrapper.apply(params.get(ZhjdDataFilter.DATA_FILTER_SQL).toString());
        }
        queryWrapper.orderByAsc("match_code");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @ZhjdDataFilter(tableAlias = "t1")
    public List<AsphaltMatchSelectDto> listSelect(Map<String, Object> params) {
        return baseMapper.listSelect(params);
    }

    @Override
    public AsphaltMatchEntity getByCode(String matchCode) {
        if (ObjectUtils.isEmpty(matchCode)) {
            return null;
        }
        QueryWrapper<AsphaltMatchEntity> queryWrapper = new QueryWrapper<AsphaltMatchEntity>();
        queryWrapper.eq("match_code", matchCode);
        List<AsphaltMatchEntity> list = baseMapper.selectList(queryWrapper);
        if (null == list || 1 != list.size()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public AsphaltMatchDetsilsDto getDetails(String id) {
        AsphaltMatchDetsilsDto dto = baseMapper.getDetails(id);
        if(null != dto) {
            return ConvertDictUtils.formatDicData(dto);
        }
        return null;
    }

    @Override
    public boolean save(AsphaltMatchEntity entity) {
        // 判断配比编码是否重复
        QueryWrapper<AsphaltMatchEntity> queryWrapper = new QueryWrapper<AsphaltMatchEntity>();
//        queryWrapper.eq("station_code", entity.getStationCode());
        queryWrapper.eq("match_code", entity.getMatchCode());
        Integer count = baseMapper.selectCount(queryWrapper);
        if (null != count && 0 < count) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "配方编号[" + entity.getMatchCode() + "]已经存在");
        }

        // 判断拌合楼是否存在
        SysStationEntity stationEntity = sysStationService
                .getOne(new QueryWrapper<SysStationEntity>().eq("code", entity.getStationCode()));
        if (null == stationEntity) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "拌合楼不存在");
        }

        // 判断配方名称是否存在
        AsphaltMatchNameEntity matchNameEntity = asphaltMatchNameService.getByName(entity.getMatchName());
        if (null == matchNameEntity) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "配方名称不存在");
        }

        // 执行添加操作
        entity.setBaseCode(stationEntity.getBaseCode());
        entity.setStationCode(stationEntity.getCode());
        entity.setMatchType(matchNameEntity.getType());
        entity.setMatchName(matchNameEntity.getName());
        entity.setHotConfig(0);
        entity.setColdConfig(0);
        return super.save(entity);
    }

    @Override
    public void updateHotConfig(String id, int state) {
        UpdateWrapper<AsphaltMatchEntity> updateWrapper = new UpdateWrapper<AsphaltMatchEntity>();
        updateWrapper.eq("id", id);
        updateWrapper.set("hot_config", state);
        baseMapper.update(null, updateWrapper);
    }

    @Override
    public void updateColdConfig(String id, int state) {
        UpdateWrapper<AsphaltMatchEntity> updateWrapper = new UpdateWrapper<AsphaltMatchEntity>();
        updateWrapper.eq("id", id);
        updateWrapper.set("cold_config", state);
        baseMapper.update(null, updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        // 获取要删除的数据
        AsphaltMatchEntity entity = baseMapper.selectById(id);
        if (null == entity) {
            return true;
        }

        // 判断级配是否在用
        QueryWrapper<AsphaltDataEntity> queryWrapper = new QueryWrapper<AsphaltDataEntity>();
        queryWrapper.eq("station_code", entity.getStationCode());
        queryWrapper.eq("match_code", entity.getMatchCode());
        Integer count = asphaltDataService.count(queryWrapper);
        if (null != count && 0 < count) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "当前生产配比正在使用，不可删除");
        }

        // 删除热料信息
        asphaltMatchHotService.deleteByMatchId(id);

        // 删除冷料信息(冷料跟配比是一对一对应的)
        asphaltMatchColdService.removeById(id);

        // 删除级配
        return super.removeById(id);
    }

    @Override
    public int saveAsphaltMatch(AsphaltMatchEntity entity) {
        SysStationEntity stationByCode = sysStationService.getStationByCode(entity.getStationCode());
        Assert.notNull(stationByCode, "请重新选择拌合楼！");
        entity.setBaseCode(stationByCode.getBaseCode());
        QueryWrapper<AsphaltMatchEntity> query = new QueryWrapper<AsphaltMatchEntity>();
        query.eq("station_code", entity.getStationCode()).eq("match_code", entity.getMatchCode());
        Integer num = baseMapper.selectCount(query);
        if (num > 0) {
            RenExceptionUtils.throwEx("配方编号已存在，请重新输入！");
        }
        return baseMapper.insert(entity);
    }
}
